/*****************************************************************************************
 **  Author:COCO 2022
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import { getDatakey } from '@/uitils/utils'
import { getNowDate } from '@/uitils/dateFormatUtil'
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: '',
    modelBody: '',
    modelFooter: '',
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {
      //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      //显示序号(默认隐藏)
      const { permission } = this.$store.getters.getPermission(
        '/Production_OSPurchaseOrder'
      )
      this.columnIndex = true
      this.boxOptions.labelWidth = 150
      this.boxButtons.forEach((item) => {
        if (item.value == 'save') {
          item.onClick = async () => {
            const isVali = this.validateForm()
            if (this.currentAction == 'Add') {
              if (isVali) {
                const res = await this.http.post(
                  '/api/Production_OSPurchaseOrder/AddOSPurchase',
                  this.editFormFields,
                  true
                )
                if (res.status) {
                  this.$message.success('新建成功')
                  this.boxModel = false
                  this.search()
                } else {
                  this.$message.error(res.message)
                }
              }
            } else {
              if (isVali) {
                // console.log(this.editFormFields)
                const { ProcessMessage, Price, OSPurchase_Id, DeliveryDate } =
                  this.editFormFields

                const res = await this.http.post(
                  `/api/Production_OSPurchaseOrder/UpdateOSPurchase?ProcessMessage=${ProcessMessage}&Price=${Price}&Id=${OSPurchase_Id}&DeliveryDate=${DeliveryDate}`,
                  null,
                  true
                )
                if (res.status) {
                  this.$message.success('修改成功')
                  this.boxModel = false
                  this.search()
                } else {
                  this.$message.error(res.message)
                }
              }
            }
          }
        }
      })

      this.columns.unshift({
        title: '操作',
        field: 'action',
        width: 120,
        render: (h, { row }) => {
          let dom1 = ''
          if (permission.includes('Print')) {
            dom1 = (
              <el-link
                underline={false}
                type="primary"
                onClick={() => this.print(row)}
              >
                <i class="el-icon-printer" />
                打印
              </el-link>
            )
          }
          return h('div', [dom1])
        },
      })
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      if (this.currentAction == 'update') {
        this.editFormOptions.forEach((item) => {
          item.forEach((x) => {
            if (x.field !== 'Price') {
              x.disabled = true
            }
            if (x.field == 'ProcessMessage' || x.field == 'DeliveryDate') {
              x.disabled = false
            }
          })
        })
      } else {
        this.editFormOptions.forEach((item) => {
          item.forEach((x) => {
            if (x.field == 'OSPurchase_Id' || x.field == 'ProcessMessage') {
              x.disabled = true
            } else {
              x.disabled = false
            }
          })
        })
      }
    },
    validateForm() {
      let flag = true
      for (const key in this.editFormFields) {
        if (key !== 'ProcessMessage' && key !== 'OSPurchase_Id') {
          if (
            this.editFormFields[key] == '' ||
            this.editFormFields[key] == null ||
            this.editFormFields[key] == undefined
          ) {
            // console.log(this.editFormFields[key], key)
            // console.log(this.editFormFields)
            this.$message.error('请填写完整信息')
            flag = false
            return
          }
        }
      }
      return flag
    },
    async print(row) {
      console.log(row)
      const data = await this.getOutRawMaterialList(row)
      const res = await getDatakey(['tips'])
      const mainData = {
        MoCode: row.MoCode,
        Supplier: row.SupplierName,
        From: '昆山鸿永峻精密五金电子科技有限公司',
        date: getNowDate(),
        To: row.Address,
        Phone: row.Phone,
      }
      const printData = {
        requestDetail: data,
        detailData: row,
        tipsData: res[0].data,
        mainData,
      }
      this.printTemplate(printData)
    },
    async getOutRawMaterialList(row) {
      const { MoCode: OrderNum, WoCode } = row
      const res = await this.http.get(
        `/api/Production_OSPurchaseOrder/GetOutRawMaterialList?OrderNum=${OrderNum}&WoCode=${
          WoCode || ''
        }`,
        null,
        true
      )
      return res
    },
    printTemplate({ mainData, requestDetail, tipsData, detailData }) {
      console.log(detailData)
      console.log(requestDetail)
      let printWindow = window.open('', '_blank')
      printWindow.document.open()
      const { MoCode, Supplier, From, date, To, Phone } = mainData
      let style = `<style>
                      p {
                        margin-block-start: 0;
                        margin-block-end: 0;
                      } 

                      .title {
                        text-align:center;
                        position: relative;
                        margin: 5px 0;
                      }

                      .header {
                        font-size: 14px;
                      }

                      .t_head {
                        flex: 1;
                        display: flex;
                      }

                      .t_head .th_item {
                        display: flex; 
                        list-style: none;
                        flex-direction: column;
                        flex: 1;
                      }

                      .t_head .th_item .th_title {
                        flex: 1; 
                        display: flex; 
                        justify-content: center;
                      }

                      .th_title .th_title_space {
                        display: flex; 
                        flex: 1;
                        flex-direction: column;
                        justify-content: flex-end;
                      }

                      .label {
                        display: flex;
                        align-items: flex-end;
                        text-align: left;
                      }

                      #qrcodeImg {
                        width: 100px; 
                        height: 100px;
                        margin-left: 10px;
                      }

                      .grid_table {
                        width: 100%; 
                        border: 1px solid #000; 
                        border-collapse: collapse;
                        font-size: 12px;
                        margin-top: 10px;
                      }

                      .grid_table tr,.grid_table tr td{
                        border: 1px dotted black;
                      }

                      .grid_table tbody {
                        text-align:center;
                      }

                      .footer {
                        display: flex; 
                        justify-content: space-between; 
                        list-style: none;
                        font-size: 12px;
                      }

                      .footer_space {
                        margin-left: 30px;
                        display: inline-block; 
                        width: 150px; 
                        border-bottom: 1px solid #000;
                      }

                      .version {
                        margin-top: 15px;
                      }

                      .cb {
                        margin-left: 20px;
                        text-align: left;
                      }

                      .tips {
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;
                      }

                      .remark {
                        text-align: center;
                        margin-top: 10px;
                      }
                    </style>`

      let title = `<div>
                        <h2 class="title">昆山鸿永峻精密五金电子科技有限公司</h2>
                        <h3 class="title">委外订单</h3>
                    </div>`

      let header = `<div class="header">
                        <div class="t_head">
                          <ul class="th_item">
                            <li class="th_title">
                              <span class="label"> P.O.NO: </span>
                              <span class="th_title_space" style="margin-left: 5px;">${MoCode}</span>
                            </li>
                            <li class="th_title">
                              <span class="label"> TO : </span>
                              <span class="th_title_space" style="margin-left: 5px;">${To}</span>
                            </li>
                            <li class="th_title">
                              <span class="label"> FROM : </span>
                              <span class="th_title_space" style="margin-left: 5px;">${From}</span>
                            </li>
                          </ul>

                          <ul class="th_item">
                            <li class="th_title">
                              <span class="label"> 日期: </span>
                              <span class="th_title_space" style="margin-left: 5px;">${date}</span>
                            </li>
                            <li class="th_title">
                              <span class="label"> 电话: </span>
                              <span class="th_title_space" style="margin-left: 5px;">${Phone}</span>
                            </li>
                            <li class="th_title">
                              <span class="label"></span>
                              <span class="th_title_space" style="margin-left: 5px;"></span>
                            </li>
                          </ul>
                        </div>
                    </div>`

      let tipItems = ''
      tipsData.forEach((item, index) => {
        tipItems += `<p class="tips_item">${item.value}</p>`
      })

      let tips = `<div class="tips">
                      <div class="tip_box">
                        <p class="tips_item">注意事项：</p>
                        ${tipItems}
                      </div>
                  </div>`

      let footer = `<div>
                      <ul class="footer"> 
                        <li>
                          供应商
                          <span class="footer_space">${Supplier}</span>
                        </li>
                        <li>
                          核准
                          <span class="footer_space"></span>
                        </li>
                        <li>
                          审核
                          <span class="footer_space"></span>
                        </li>
                        <li>
                          经办人
                          <span class="footer_space"></span>
                        </li>
                      </ul>
                  <div>`
      let table = ''
      let detailTable = ''
      let main = ''
      let detail = ''

      main += `
          <tr>
            <td>1</td>
            <td>${detailData.ProductName}</td>
            <td>${detailData.DeliveryDate}</td>
            <td>${detailData.Unit}</td>
            <td>${detailData.Qty}</td>
            <td>${detailData.Price}</td>
            <td>${detailData.Qty * detailData.Price}</td>
            <td>${detailData.ProcessMessage || ''}</td>
          </tr>`

      requestDetail.forEach((item, index) => {
        detail += `<tr>
            <td>${index + 1}</td>
            <td>${item.productName}</td>
            <td>${item.specification || ''}</td>
            <td>${item.unit}</td>
            <td>${item.qnty}</td>
            <td>${item.outQnty}</td>
            <td>${item.singleWeight}</td>
            <td>${item.outQnty * item.singleWeight}</td>
            `
      })

      table += `
      <table class="grid_table">
        <thead>
          <tr>
            <th>序号</th>
            <th>物料名称</th>
            <th>交货日期</th>
            <th>单位</th>
            <th>委外数量</th>
            <th>含税单价</th>
            <th>含税总金额</th>
            <th>加工要求</th>
          </tr>
        </thead>
        <tbody>
          ${main}
        </tbody>
      </table>`

      detailTable += `
      <table class="grid_table">
        <caption>领料明细</caption>
        <thead>
          <tr>
            <th>序号</th>
            <th>品名</th>
            <th>规格</th>
            <th>单位</th>
            <th>应领料数量</th>
            <th>已领料数量</th>
            <th>单耗</th>
            <th>实际重量</th>
          </tr>
        </thead>
        <tbody>
          ${detail}
        </tbody>
      </table>
      `

      printWindow.document.write(
        `<html><head><title>Print</title>${style}</head><body>`
      )
      printWindow.document.write(title)
      printWindow.document.write(header)
      printWindow.document.write(tips)
      printWindow.document.write(table)
      printWindow.document.write(requestDetail.length ? detailTable : '')
      printWindow.document.write(
        `<div class="remark">注:送货单请写明委外订单号，数量不得超委外数量单，否则我司将拒收</div>`
      )
      printWindow.document.write(footer)
      printWindow.document.close()
      setTimeout(() => {
        printWindow.print()
        printWindow.close()
      }, 100)
    },
  },
}
export default extension
